from peewee import *
from models.BaseModel import BaseModel
from util.Model2Dict import m2d
from entry.Entrys import Page
""" 角色表 """
class Role(BaseModel):
    rId = BigIntegerField(db_column='r_id',primary_key =True)
    name = CharField(db_column='name')
    key = CharField(db_column='key')
    status = CharField()
    initBy = BigIntegerField(db_column='init_by')
    initTime = DateTimeField(db_column='init_time')
    updateBy = BigIntegerField(db_column='update_by')
    updateTime = DateTimeField(db_column='update_time')
    sys = CharField()
    indexPath = CharField(db_column='index_path')
    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_role'

""" 角色操作权限映射 """
class RoleHandleMapping(BaseModel):
    rId = BigIntegerField(db_column='r_id')
    hId = BigIntegerField(db_column='h_id')

    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_role_handle'
        
""" 角色菜单路由映射 """
class RoleMemuMapping(BaseModel):
    rId = BigIntegerField(db_column='r_id')
    mId = BigIntegerField(db_column='m_id')

    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_role_menu'
 
""" 角色菜单按钮映射表"""
class RoleMemuHandleMapping(BaseModel):
    rId = BigIntegerField(db_column='r_id')
    tag = CharField(db_column='tag')

    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_role_menu_handle'  
 
""" 获取所有的角色 """
def getAllRole(page:Page = Page(),cdn=dict()):
    query = Role.select()
    if cdn.get('key'):
        query = query.where(Role.key == cdn.get('key'))
    if cdn.get('status'):
        query = query.where(Role.status == cdn.get('status'))
    if cdn.get('name'):
        query = query.where(Role.name.contains(cdn.get('name')))
    r = query.paginate(page.num,page.size).dicts()
    page.count = query.count()
    page.rows = m2d(r)
    return page.__dict__

""" 获取所有的角色名 """
def getAllRoleName(page:Page = Page()):
    r = Role.select(Role.rId,Role.name).paginate(page.num,page.size).dicts()
    page.count = Role.select().count()
    page.rows = m2d(r)
    return page.__dict__

# 获取角色id列表里 的所有角色名
def getRoleNameInIsd(rids:list[int]):
    return m2d(Role.select(Role.rId,Role.name,Role.status,Role.indexPath).where(Role.rId.in_(rids)).dicts())

def updateRole(id,k):
    return Role.update(k).where(Role.rId == id).execute()>0

""" 添加新的角色 """
def addRole(d:dict):
    return Role.insert(d).execute() 

""" 删除角色 """
def delRoleInId(id:list[int]):
    return Role.delete().where(Role.rId.in_(id)).execute() > 0

# 根据查询 id list 里的 角色
def getRolesInId(ids:list[int]):
    results = Role.select().where(Role.rId.in_(ids)).dicts()
    return m2d(results)

def getCanUseRoleIdsInId(ids:list[int]):
    results = Role.select(Role.rId).where(Role.rId.in_(ids),Role.status == '1').dicts()
    return [item['rId'] for item in m2d(results)]

""" 查询角色使用状态 """
def getRoleStatus(id):
    result = Role.select(Role.status).where(Role.rId == id).dicts().execute()
    if(len(result)>0):
        return m2d(result)[0]["status"]
    else:
        return None

""" 查询角色的菜单权限ids """
def getRoleMenusIds(id)->list[int]:
    menus:list[RoleMemuMapping] = RoleMemuMapping.select(RoleMemuMapping.mId).where(RoleMemuMapping.rId == id).dicts().execute()
    return [item["mId"] for item in m2d(menus)]

""" 查询角色所有的操作权限ids """
def getRoleHandles(id) -> list[int]:
    handles:list[RoleHandleMapping] = RoleHandleMapping.select(RoleHandleMapping.hId).where(RoleHandleMapping.rId == id).dicts().execute()
    return [item["hId"] for item in m2d(handles)]



def delRoleMenuInRid(rids:list[int]):
    count = RoleMemuMapping.delete().where(RoleMemuMapping.rId.in_(rids)).execute()
    if count>0:
        return True
    return False

""" 为用户添加操作 """
def addRoleHandle(rid:int,hids:list[int]):
    d = list()
    for item in hids:
        d.append({"rId":rid,"hId":item})
    if(len(d)>0):
        RoleHandleMapping.insert_many(d).execute()
    return True

""" 为用户添加菜单 """
def addRoleMenu(rid:int,mids:list[int]):
    d = list()
    for item in mids:
        d.append({"rId":rid,"mId":item})
    if(len(d)>0):
        RoleMemuMapping.insert_many(d).execute()
    return True

""" 判断是否拥有该角色 """
def hasRole(rid) -> bool:
    return Role.select(Role.rId).where(Role.rId == rid).count()>0

""" 查询是否拥有某菜单权限 """
def hasRoleMenu(rid:int,mid:int)->bool:
    if RoleMemuMapping.select(RoleMemuMapping.mId).where(RoleMemuMapping.rId ==rid,RoleMemuMapping.mId==mid).count()>0:
        return True
    return False

""" 查询是否拥有某接口操作权限 """
# 检查这些角色里是否拥有接口权限
def hasRolesHandle(rids:list[int],hid:int)->bool:
    if RoleHandleMapping.select(RoleHandleMapping.hId).where(RoleHandleMapping.rId.in_(rids), RoleHandleMapping.hId ==hid).count() > 0:
        return True
    return False

# 删除所有有hid 的映射关系
def delRoleHandleInHid(hids:list[int]):
    return RoleHandleMapping.delete().where(RoleHandleMapping.hId.in_(hids)).execute()


# 批量删除所有角色拥有的接口映射关系
def delRoleHandleInRid(rids:list[int]):
    return RoleHandleMapping.delete().where(RoleHandleMapping.rId.in_(rids)).execute()


# 批量删除所有有角色菜单映射关系
def delRoleMenuInMid(mids:list[int]):
    return RoleMemuMapping.delete().where(RoleMemuMapping.mId.in_(mids)).execute()

# 删除所有有rid 的映射关系
def delRoleMenuInRid(rids:list[int]):
    return RoleMemuMapping.delete().where(RoleMemuMapping.rId.in_(rids)).execute()



""" 角色菜单按钮 """
# 根据角色获取角色拥有的所有按钮id
def getRoleMenuHandleAll(rid:int)->list[str]:
    r = RoleMemuHandleMapping.select(RoleMemuHandleMapping.tag).where(RoleMemuHandleMapping.rId == rid).dicts()
    return [item['tag'] for item in m2d(r)] 

# 清空角色用户菜单按钮(根据角色id)
def delRoleMenuHandleInRid(rid:list[int]):
    return RoleMemuHandleMapping.delete().where(RoleMemuHandleMapping.rId.in_(rid)).execute()

def delRoleMenuHandleInTag(tag:list[str]):
    return RoleMemuHandleMapping.delete().where(RoleMemuHandleMapping.tag.in_(tag)).execute()

# 添加角色用户菜单按钮
def addRoleMenuHandle(rid,tags:list[str]):
    d = list()
    for item in tags:
        d.append({"rId":rid,"tag":item})
    if(len(d)>0):
        RoleMemuHandleMapping.insert_many(d).execute()
    return True
